<?php
// +----------------------------------------------------------------------
// | JSHOP [ 小程序商城 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019 http://jihainet.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: keinx <keinx@jihainet.com>
// +----------------------------------------------------------------------
namespace app\api\controller;
use app\common\controller\Api;
use app\common\model\BillLading;
use app\common\model\Clerk;
use app\common\model\Setting;
use app\common\model\Store as Model;
use app\common\model\Order as orderModel;
use org\Wx;
use think\facade\Request;
use think\Validate;
use app\common\model\GoodsExtendCat;
use app\common\model\GoodsGrade;
use app\common\model\UserGrade;
use app\common\model\Goods as goodsModel;
use app\common\model\GoodsType;
use app\common\model\GoodsCat;
use app\common\model\Brand;
use app\common\model\Products;
use app\common\model\GoodsImages;
use app\common\model\GoodsTypeParams;
use think\Db;
use app\common\validate\Goods as GoodsValidate;
use app\common\validate\Products as ProductsValidate;
use app\common\model\User as UserModel;

/**
 * 门店
 * Class Store
 * @package app\api\controller
 */
class Store extends Api
{
    /**
     * 判断是否开启门店自提
     * @return array
     */
    public function getStoreSwitch()
    {
        $return = [
            'status' => true,
            'msg' => '获取成功',
            'data' => 2
        ];
        $settingModel = new Setting();
        $return['data'] = $settingModel->getValue('store_switch');
        return $return;
    }


    /**
     * 获取默认店铺
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDefaultStore()
    {
        $model = new Model();
        return $model->getDefaultStore();
    }


    /**
     * 获取店铺列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getStoreList()
    {
        $model = new Model();
        $key = Request::param('key', '');
        $longitude = Request::param('longitude', false);
        $latitude = Request::param('latitude', false);
        return $model->getAllStoreList($key, $longitude, $latitude);
    }


    /**
     * 是否是店员
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function isClerk()
    {
        $model = new Clerk();
        return $model->isClerk($this->userId);
    }


    /**
     * 店铺提货单列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function storeLadingList()
    {
        $model = new BillLading();
        return $model->getStoreLadingList($this->userId);
    }


    /**
     * 提货单详情
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ladingInfo()
    {
        $key = Request::param('key');
        $model = new BillLading();
        return $model->getInfo($key, $this->userId);
    }

    /**
     * 提单操作
     * @return array
     */
    public function lading()
    {
        $lading_ids = Request::param('lading_ids');
        $model = new BillLading();
        return $model->ladingOperating($lading_ids, $this->userId);
    }

    /**
     * 提货单删除
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ladingDel()
    {
        $lading_id = Request::param('lading_id');
        $model = new BillLading();
        return $model->del($lading_id, $this->userId);
    }

    /**
     * 获取邀请小程序码
     * @return array
     */
    public function getInviteQRCode()
    {
        $invite = Request::param('invite', 0);
        $type = Request::param('type', 'index');
        $goods = Request::param('goods', 0);
        $page = 'pages/index/index';
        if($type == 'goods')
        {
            $page = 'pages/goods/detail/detail';
        }
        $wx = new Wx();
        $wx_appid = getSetting('wx_appid');
        $wx_app_secret = getSetting('wx_app_secret');
        $accessToken = $wx->getAccessToken($wx_appid, $wx_app_secret);
        if($accessToken)
        {
            $style['width'] = 300;
            return $wx->getParameterQRCode($accessToken, $page, $invite, $goods, $style, $wx_appid);
        }
        else
        {
            return $return = [
                'status' => false,
                'msg' => '后台小程序配置的APPID和APPSECRET错误，无法生成海报',
                'data' => ''
            ];
        }
    }
    /**
     * 获取推荐关键词
     * @return array
     */
    public function getRecommendKeys()
    {
        $recommend_keys = getSetting('recommend_keys');
        $recommend_keys = explode(' ', $recommend_keys);
        $result = [
            'status' => true,
            'msg' => '获取成功',
            'data' => $recommend_keys
        ];
        return $result;
    }
    /**
     * 门店添加
     * @param array $data
     * @return array
     */
    public function addData($data = [])
    {
        $result = ['status' => true, 'msg' => '保存成功','data' => ''];
        $validate = new Validate($this->rule,$this->msg);
        if(!$validate->check($data))
        {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        }
        else
        {
            if(!$this->allowField(true)->save($data))
            {
                $result['status'] = false;
                $result['msg'] = '保存失败';
            }
        }
        return $result;
    }
    /**
     * 商户端获取订单相关
     * author:rz
     */
    public function getOrderlist()
    {
        $input = array(
        'status'  => input('status'),
        'page'    => input('page'),
        'limit'   => input('limit'),
        'user_id' => input('store_id/d',0),
    );
        if (empty($input['user_id'] || $input['user_id']<=0)){
            return [
                'status' => true,
                'msg'    => '参数错误',
                'data'=>''
            ];
        }
        //判断用户是不是商户等级
        if (db('user')->where(['id'=>1])->value('grade') == 2){
            $model = new orderModel();
            $data  = $model->getListFromWxApi($input);
            $return_data = array(
                'status' => true,
                'msg'    => '获取成功',
                'data'   => array(
                    'list'   => $data['data'],
                    'count'  => $data['count'],
                    'page'   => $input['page'],
                    'limit'  => $input['limit'],
                    'status' => $input['status']
                )
            );
            return $return_data;
        }else{
            return array(['code'=>false,'msg'=>'您没有商户权限','data'=>[]]);
        }
    }
    /**
     * 商户添加商品
     */
    public function addGoods()
    {
        $result = [
            'status' => false,
            'msg'    => '',
            'data'   => '',
        ];
        $goods_id = input('param.goods_id/d',0);
        $is_edit = input('param.is_edit',false);
        $iseditflag = false;
        //商品数据组装并校检
        //编辑商品
        if ($is_edit){
            if (empty($goods_id) || $goods_id<=0){
                return [
                    'status' => false,
                    'msg'    => '商品ID不能为空',
                    'data'   => '',
                ];
            }
            $iseditflag = true;
        }else{
            $iseditflag = false;
        }
        $checkData = $this->checkGoodsInfo($iseditflag);
        if (!$checkData['status']) {
            $result['msg'] = $checkData['msg'];
            return $result;
        }
        $data = $checkData['data'];
        //验证商品数据
        $goodsModel    = new goodsModel();
        $productsModel = new Products();
        $goodsModel->startTrans();
        //编辑商品
        if ($iseditflag){
            if ($goodsModel->updateGoods($goods_id,$data['goods'])){
                $goods_id = 0;
            }
        }else{
            //添加商品
            $goods_id = $goodsModel->doAdd($data['goods']);
            if (!$goods_id) {
                $goodsModel->rollback();
                $result['msg'] = '商品数据保存失败';
                return $result;
            }
        }
        //保存会员价
        $grade_price = input('post.goods.grade_price/a', []);
        if ($grade_price) {
            $grade_price_arr = [];
            foreach ($grade_price as $key => $value) {
                $grade_price_arr[] = [
                    'goods_id'    => $goods_id,
                    'grade_id'    => $key,
                    'grade_price' => $value,
                ];
            }
            $goodsGrade = new GoodsGrade();
            $goodsGrade->where(['goods_id' => $goods_id])->delete();
            if (!$goodsGrade->saveAll($grade_price_arr)) {
                $goodsModel->rollback();
                $result['msg'] = '会员价保存失败';
                return $result;
            }
        }

        //保存图片
        if (isset($data['images']) && count($data['images']) > 1) {
            $imgRelData = [];
            $i          = 0;
            foreach ($data['images'] as $key => $val) {
                if ($key == 0) {
                    continue;
                }
                $imgRelData[$i]['goods_id'] = $goods_id;
                $imgRelData[$i]['image_id'] = $val;
                $imgRelData[$i]['sort']     = $i;
                $i++;
            }
            $goodsImagesModel = new GoodsImages();
            if (!$goodsImagesModel->batchAdd($imgRelData, $goods_id)) {
                $goodsModel->rollback();
                $result['msg'] = '商品图片保存失败';
                return $result;
            }
        }
        //保存商品扩展分类
        $goodsExtendCat = new GoodsExtendCat();
        if (!$goodsExtendCat->saveCat($data['extend_cat'], $goods_id)) {
            $goodsModel->rollback();
            $result['msg'] = '扩展分类保存失败';
            return $result;
        }

        //更新商品总库存
        $total_stock          = $productsModel->where([['goods_id', '=', $goods_id]])->sum('stock');
        $upDataGoods['stock'] = $total_stock;
        $res                  = $goodsModel->updateGoods($goods_id, $upDataGoods);
        if ($res === false) {
            $goodsModel->rollback();
            $result['msg'] = '总库存更新失败';
            return $result;
        }
        $goodsModel->commit();

        array_push($data, ['goods_id' => $goods_id]);
        hook('addgoodsafter', $data);//添加商品后增加钩子

        $result['msg']    = '保存成功';
        $result['status'] = true;
        return $result;
    }
    private function checkGoodsInfo($isEdit = false)
    {
        $result = ['status' => false, 'msg'    => '', 'data'   => ''];
        $bn                             = get_sn(3);
        if (empty($data['goods']['bn'])) {  $data['goods']['bn'] = $bn;}
        $data['goods']['name']          = input('post.name', '');
        $data['goods']['goods_cat_id']  = input('post.goods_cat_id', '0');
        $data['goods']['goods_type_id'] = input('post.goods_type_id', 0);
        $store_id = input('param.store_id', 0);
        if (empty($store_id || $store_id<=0)){
            return [
                'status' => true,
                'msg'    => '参数错误',
                'data'=>''
            ];
        }
        $data['goods']['brand_id']      = db('brand')->where(['name'=>db('store')->where(['id'=>$store_id])->value('brand')])->value('id');
        $data['goods']['bn']            = input('post.bn', $bn);
        $data['goods']['store_id']            = $store_id;
        $data['goods']['type']            = 2;
        $data['goods']['brief']        = input('post.brief', '');
        $data['goods']['intro']        = input('post.intro', '');
        $data['goods']['price']        = input('post.price', '');
        $data['goods']['costprice']    = input('post.costprice', '');
        $data['goods']['mktprice']     = input('post.mktprice', '');
        $data['goods']['weight']       = input('post.weight', '');
        $data['goods']['stock']        = input('post.stock', '');
        $data['goods']['unit']         = input('post.unit', '');
        $data['goods']['marketable']   = input('post.marketable', '2');
        $data['goods']['is_recommend'] = input('post.is_recommend', '2');
        $data['goods']['is_hot']       = input('post.is_hot', '2');
        $open_spec                     = input('post.open_spec', 0);
        $specdesc                      = input('post.spec/a', []);
        $new_spec                      = input('post.new_spec/a', []);//自定义规格
        $data['goods']['spes_desc'] = serialize($specdesc);
        $data['goods']['new_spec']  = serialize($new_spec);
        $images = input('post.img/a', []);
        /*if (count($images) <= 0) {
            $result['msg'] = '请先上传图片';
            return $result;
        }*/
        $data['goods']['image_id'] = reset($images);
        $data['images']            = $images;
        $goodsModel                = new goodsModel();
        if ($isEdit) {
            $data['goods']['id'] = input('post.goods_id/d', 0);
            $validate            = new GoodsValidate();
            if (!$validate->scene('edit')->check($data['goods'])) {
                $result['msg'] = $validate->getError();
                return $result;
            }
        } else {
            $validate = new GoodsValidate();
            if (!$validate->check($data['goods'])) {
                $result['msg'] = $validate->getError();
                return $result;
            }
        }

        $result['data']   = $data;
        $result['status'] = true;
        return $result;
    }
    /**
     * User: wjima
     * Email:1457529125@qq.com
     * Date: 2018-01-23 11:32
     */
    public function getSpec()
    {
        $result = [
            'status' => false,
            'msg'    => '关键参数丢失',
            'data'   => '',
        ];
        $this->view->engine->layout(false);
        $type_id = input('post.type_id');
        if (!$type_id) {
            return $result;
        }
        $goodsTypeModel = new GoodsType();
        $res            = $goodsTypeModel->getTypeValue($type_id);

        $html       = '';
        $customSpec = false;//是否可以使用自定义规格
        if ($res['status'] == true) {
            $this->assign('typeInfo', $res['data']);
            if (!$res['data']['spec']->isEmpty()) {
                $spec = [];
                foreach ($res['data']['spec']->toArray() as $key => $val) {
                    $spec[$key]['name']      = $val['spec']['name'];
                    $spec[$key]['specValue'] = $val['spec']['getSpecValue'];
                }
                $this->assign('spec', $spec);
                if (count($spec) <= 2) {//规格超过2种的，不允许自定义
                    $customSpec = true;
                }
            }
            $this->assign('customSpec', $customSpec);

            if ($res['data']['spec']->isEmpty()) {
                $this->assign('canOpenSpec', 'false');
            } else {
                $this->assign('canOpenSpec', 'true');
            }
            //erp同步插件是否开启
            $addonsModel = new \app\common\model\Addons();
            $addons      = $addonsModel->where('name', 'eq', 'ErpSyn')->find();
            if ($addons) {
                $erp_syn_on = true;
            } else {
                $erp_syn_on = false;
            }
            $this->assign('erp_syn_on', $erp_syn_on);
            //获取参数信息
            $goodsTypeParamsModel = new GoodsTypeParams();
            $typeParams           = $goodsTypeParamsModel->getRelParams($type_id);
            $this->assign('typeParams', $typeParams);
            $html             = $this->fetch('getSpec');
            $result['status'] = true;
            $result['msg']    = '获取成功';
            $result['data']   = $html;
        }
        return $result;
    }
    /***
     * 生成多规格html
     * @return array
     * User: wjima
     * Email:1457529125@qq.com
     * Date: 2018-01-23 15:34
     */
    public function getSpecHtml()
    {
        $result = [
            'status' => false,
            'msg'    => '关键参数丢失',
            'data'   => '',
        ];
        $this->view->engine->layout(false);
        $spec         = input('post.spec/a');
        $goods_id     = input('post.goods_id/d', 0);
        $goodsDefault = input('post.goods/a', []);
        $products     = [];
        if ($goods_id) {
            $goodsModel = new goodsModel();
            $goods      = $goodsModel->getOne($goods_id, 'id,image_id');
            if (!$goods['status']) {
                return '商品不存在';
            }
            $products = $goods['data']->products;
        }

        if ($spec) {
            $specValue = [];
            $total     = count($spec);
            foreach ($spec as $key => $val) {
                $this->spec[] = $key;
            }
            $items = $this->getSkuItem($spec, -1);

            foreach ((array)$items as $key => $val) {
                $items[$key]['price']     = $goodsDefault['price'];
                $items[$key]['costprice'] = $goodsDefault['costprice'];
                $items[$key]['mktprice']  = $goodsDefault['mktprice'];
                if (isset($goodsDefault['sn']) && $goodsDefault['sn']) {
                    $items[$key]['sn'] = $goodsDefault['sn'] . '-' . ($key + 1);
                }
                $items[$key]['stock'] = $goodsDefault['stock'];
            }

            if ($products) {
                foreach ($items as $key => $val) {
                    foreach ($products as $product) {
                        if ($val['spec_name'] == $product['spes_desc']) {
                            $items[$key]               = array_merge((array)$val, (array)$product);
                            $items[$key]['product_id'] = $product['id'];
                        }
                    }
                }
            }
            $this->assign('items', $items);
        }
        //erp同步插件是否开启
        $addonsModel = new \app\common\model\Addons();
        $addons      = $addonsModel->where('name', 'eq', 'ErpSyn')->find();
        if ($addons) {
            $erp_syn_on = true;
        } else {
            $erp_syn_on = false;
        }
        $this->assign('erp_syn_on', $erp_syn_on);
        $html             = $this->fetch('getSpecHtml');
        $result['data']   = $html;
        $result['status'] = true;
        $result['msg']    = '获取成功';
        return $result;

    }
    private function getSkuItem($data, $index = -1, $sku_item = [])
    {
        self::$total_item = array();
        if ($index < 0) {
            self::$deep_key = count($data) - 1;
            $this->getSkuItem($data, 0, $sku_item);
        } else {
            if ($index == 0) {
                $first = $data[$this->spec[$index]];

                foreach ($first as $key => $value) {
                    self::$total_item[$key] = array(
                        'spec_name' => $this->spec[$index] . ':' . $value,
                        'spec_key'  => $this->spec[$index],
                    );
                }
            } else {
                $first = $data[$this->spec[$index]];

                if (count($sku_item) >= count($first)) {
                    foreach ($first as $key => $value) {
                        foreach ($sku_item as $s => $v) {

                            self::$total_item[] = array(
                                'spec_name' => $v['spec_name'] . ',' . $this->spec[$index] . ':' . $value,
                                'spec_key'  => $v['spec_key'] . '_' . $this->spec[$index],
                            );
                        }
                    }
                } else {
                    if ($sku_item) {
                        foreach ($sku_item as $key => $value) {
                            foreach ($first as $fkey => $fvalue) {
                                self::$total_item[] = array(
                                    'spec_name' => $value['spec_name'] . ',' . $this->spec[$index] . ':' . $fvalue,
                                    'spec_key'  => $value['spec_key'] . '_' . $this->spec[$index],
                                );
                            }
                        }
                    }
                }
            }
            if ($index < self::$deep_key) {
                $this->getSkuItem($data, $index + 1, self::$total_item);
            }
        }
        return self::$total_item;

    }
    /**
     * 编辑商家信息
     */
    public function editInfo()
    {
        $data['mobile'] = input('param.mobile', '');
        $store_id = input('param.store_id/d', 0);
        if(empty($store_id) || $store_id<=0){
            return ['status'=>false,'msg'=>'参数错误','data'=>''];
        }
        $data['service'] = input('param.service', '');
        $data['freight'] =  input('param.freight', '');
        $data['delivery_address'] = input('param.delivery_address', '');
        $userModel = new UserModel();
        return $userModel->editStoreInfo($store_id, $data);
    }
    /**
     * 订单发货
     */
    public function orderSend()
    {

    }
    /**
     * 获取商家商品详情
     */
    public function goodsInfo()
    {
        $store_id = input('param.store_id/d', 0);
        if(empty($store_id) || $store_id<=0){
            return ['status'=>false,'msg'=>'参数错误','data'=>''];
        }
    }

}
